package com.productivity.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Scanner;

import com.productivity.model.common.Vertex3D;

public class OBJLoader {
	public static FloatBuffer loadObjectFromFile(String fileName) {
		File f = new File(fileName);
		Scanner scan = null;
		try {
			scan = new Scanner(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		scan.nextLine();
		scan.nextLine();
		scan.nextLine();
		ArrayList<Vertex3D> verts = new ArrayList<Vertex3D>();
		ArrayList<Vertex3D> norms = new ArrayList<Vertex3D>();
		ArrayList<Face> faces = new ArrayList<Face>();
		while(scan.hasNext()) {
			String type = scan.next();
			if(type.equals("v")) {
				verts.add(new Vertex3D(scan.nextLine().split(" ")));
			}
			else if(type.equals("vn")) {
				norms.add(new Vertex3D(scan.nextLine().split(" ")));
			}
			else if(type.equals("f")) {
				faces.add(new Face(scan.nextLine().split(" ")));
			}
			else scan.nextLine();
		}
		FloatBuffer buff = FloatBuffer.allocate(faces.size()*18);
		for(int i = 0; i < faces.size();i++) {
			buff.put(verts.get(faces.get(i).verts[0]).getArray());
			buff.put(norms.get(faces.get(i).norms[0]).getArray());
			buff.put(verts.get(faces.get(i).verts[1]).getArray());
			buff.put(norms.get(faces.get(i).norms[1]).getArray());
			buff.put(verts.get(faces.get(i).verts[2]).getArray());
			buff.put(norms.get(faces.get(i).norms[2]).getArray());
		}
		buff.rewind();
		return buff;
	}
}

class Face {
	public int[] verts;
	public int[] norms;
	public Face(String[] elements) {
		verts = new int[3];
		norms = new int[3];
		norms[0] = Integer.parseInt(elements[1].split("//")[1])-1;
		verts[0] = Integer.parseInt(elements[1].split("//")[0])-1;
		norms[1] = Integer.parseInt(elements[2].split("//")[1])-1;
		verts[1] = Integer.parseInt(elements[2].split("//")[0])-1;
		norms[2] = Integer.parseInt(elements[3].split("//")[1])-1;
		verts[2] = Integer.parseInt(elements[3].split("//")[0])-1;
	}
}
